// src/info/CustomModal.tsx
import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import React from 'react';
import { useRouter } from 'expo-router';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import Modal from 'react-native-modal';
import { usePayContext  } from '../AppContext';

interface CustomModalProps {
    isVisible: boolean;
    onClose: () => void;
    children: React.ReactNode;
    parsedItem: any; // 根据实际数据类型定义
    gift: any[]; // 根据实际数据类型定义
    total: number;
}

const CustomModal: React.FC<CustomModalProps> = ({ isVisible, onClose, children, parsedItem, gift, total }) => {
    const router = useRouter();
    const { setItem, setTotal } = usePayContext();

    // 打印 parsedItem 和 total 以确保其格式正确
    console.log('Parsed Item:', JSON.stringify(parsedItem));
    console.log('Total:', total);

    const buy = () => {
        console.log('支付');
        console.log('Parsed Item String:', JSON.stringify(parsedItem));
        console.log('Total:', total);

        // 确保 total 是一个数字
        if (typeof total !== 'number') {
            console.error('Total is not a number:', total);
            return;
        }

        // 设置 Context 中的 item 和 total
        setItem(parsedItem);
        setTotal(total);

        // 导航到 pay 页面
        router.push({
            pathname: '/info/pay',
        });
    };

    return (
        <Modal isVisible={isVisible} style={styles.modal}>
            <View style={styles.modalContent}>
                {children}
                <ThemedView style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
                    <TouchableOpacity style={styles.closeButton} onPress={onClose}>
                        <Text style={styles.closeButtonText}>关闭</Text>
                    </TouchableOpacity>
                    <TouchableOpacity 
                        style={styles.closeButton} 
                        onPress={buy}
                    >
                        <Text style={styles.closeButtonText}>立即购买</Text>
                    </TouchableOpacity>
                </ThemedView>
            </View>
        </Modal>
    );
};

const styles = StyleSheet.create({
    modal: {
        justifyContent: 'flex-end',
        margin: 0,
    },
    modalContent: {
        backgroundColor: 'white',
        padding: 20,
        borderTopLeftRadius: 10,
        borderTopRightRadius: 10,
    },
    closeButton: {
        backgroundColor: '#ff4d4f',
        padding: 10,
        width: '45%',
        alignItems: 'center',
        borderRadius: 5,
        marginTop: 10,
    },
    closeButtonText: {
        color: 'white',
    },
});

export default CustomModal;